package com.xique.park.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.domain.R;
import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.AliossUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.datascope.annotation.NeedSetDictLabel;
import com.xique.common.datascope.annotation.NeedSetFieldValue;
import com.xique.park.bean.domain.ParkGarage;
import com.xique.park.bean.domain.ParkIn;
import com.xique.park.bean.domain.ParkLane;
import com.xique.park.bean.domain.ParkOn;
import com.xique.park.bean.domain.client.ClientLaneConfig;
import com.xique.park.bean.domain.client.ParkClient;
import com.xique.park.bean.request.client.ClientPlateEditRequest;
import com.xique.park.bean.request.client.OpenGateRequest;
import com.xique.park.bean.request.client.ParkClientSelectLaneRequest;
import com.xique.park.bean.vo.client.OpenGateVo;
import com.xique.park.mapper.ParkLaneMapper;
import com.xique.park.mapper.client.ClientLaneConfigMapper;
import com.xique.park.mapper.client.ParkClientMapper;
import com.xique.park.service.service.IParkClientService;
import com.xique.park.service.service.IParkGarageService;
import com.xique.park.service.service.IParkInService;
import com.xique.park.service.service.IParkOnService;
import com.xique.system.api.RemoteSystemUserService;
import com.xique.system.api.dto.OperateDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 岗亭管理Service业务层处理
 *
 * @author ww
 * @date 2019-10-15
 */
@Service
public class ParkClientServiceImpl implements IParkClientService {

    @Autowired
    private ParkClientMapper parkClientMapper;

    @Autowired
    private ParkLaneMapper parkLaneMapper;

    @Autowired
    private ClientLaneConfigMapper clientLaneConfigMapper;

    @Autowired
    private IParkOnService parkOnService;

    @Autowired
    private IParkInService parkInService;

    @Autowired
    private IParkGarageService parkGarageService;

    @Autowired
    private RemoteSystemUserService remoteSystemUserService;

    @Autowired
    private AliossUtil aliossUtil;

    /**
     * 查询岗亭管理
     *
     * @param id 岗亭管理ID
     * @return 岗亭管理
     */
    @Override
    @NeedSetFieldValue
    public ParkClient selectParkClientById(Long id) {
        return parkClientMapper.selectParkClientById(id);
    }

    /**
     * 查询岗亭管理列表
     *
     * @param parkClient 岗亭管理
     * @return 岗亭管理
     */
    @Override
    @NeedSetFieldValue
    @NeedSetDictLabel
    public List<ParkClient> selectParkClientList(ParkClient parkClient) {
        List<ParkClient> parkClientList = parkClientMapper.selectParkClientList(parkClient);
        if (CollectionUtil.isNotEmpty(parkClientList)) {
            parkClientList.forEach(client -> {
                Long updateUser = client.getUpdateUser();
                if (null != updateUser) {
                    R<OperateDTO> result = remoteSystemUserService.getOperate(updateUser);
                    if (result.getData() != null) {
                        client.setUpdateBy(result.getData().getOperateName());
                    }
                }
            });
        }
        return parkClientList;
    }

    /**
     * 新增岗亭管理
     *
     * @param parkClient 岗亭管理
     * @return 结果
     */
    @Override
    public int insertParkClient(ParkClient parkClient) {
        parkClient.setUpdateUser(SecurityUtils.getUserId());
        parkClient.setUpdateTime(new Date());
        return parkClientMapper.insertParkClient(parkClient);
    }

    /**
     * 修改岗亭管理
     *
     * @param parkClient 岗亭管理
     * @return 结果
     */
    @Override
    public int updateParkClient(ParkClient parkClient) {
        parkClient.setUpdateUser(SecurityUtils.getUserId());
        parkClient.setUpdateTime(new Date());
        return parkClientMapper.updateParkClient(parkClient);
    }

    /**
     * 删除岗亭管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteParkClientByIds(String ids) {
        return parkClientMapper.deleteParkClientByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除岗亭管理信息
     *
     * @param id 岗亭管理ID
     * @return 结果
     */
    @Override
    public int deleteParkClientById(Long id) {
        return parkClientMapper.deleteParkClientById(id);
    }

    @Override
    public List<ParkLane> selectClientLaneAllocatedList(ParkClientSelectLaneRequest request) {
        ParkLane parkLane = new ParkLane();
        parkLane.setClientId(request.getClientId());
        parkLane.setName(request.getLaneName());
        parkLane.setParkId(Long.valueOf(request.getParkId()));
        List<ParkLane> parkLanes = parkLaneMapper.selectClientLaneAllocatedList(parkLane);
        List<Long> garageIds = parkLanes.stream().map(ParkLane::getGarageId).collect(Collectors.toList());
        ParkGarage search = new ParkGarage();
        search.setGarageIds(garageIds);
        List<ParkGarage> parkGarages = parkGarageService.selectParkGarageList(SecurityUtils.getParkId(), search);
        for (ParkLane lane : parkLanes) {
            parkGarages.stream().filter(e -> e.getId().equals(lane.getGarageId())).findAny().ifPresent(parkGarage -> lane.setGarageName(parkGarage.getName()));
        }
        return parkLanes;
    }

    @Override
    public List<ParkLane> selectClientLaneUnAllocatedList(ParkClientSelectLaneRequest request) {
        ParkLane parkLane = new ParkLane();
        parkLane.setParkId(Long.valueOf(request.getParkId()));
        parkLane.setClientId(request.getClientId());
        parkLane.setName(request.getLaneName());
        ParkClient parkClient = new ParkClient();
        parkClient.setParkId(Long.valueOf(request.getParkId()));
        List<ParkClient> parkClients = parkClientMapper.selectParkClientList(parkClient);
        List<Long> clientIds = parkClients.stream().map(ParkClient::getId).collect(Collectors.toList());
        return parkLaneMapper.selectClientLaneUnAllocatedList(parkLane, clientIds);
    }

    /**
     * 批量绑定
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult addClientLaneAll(ParkClientSelectLaneRequest request) {
        String[] ids = request.getLaneIds().split(",");
        List<ClientLaneConfig> clientLaneConfigs = new ArrayList<>();
        int sort = 0;
        for (String laneId : ids) {
            ClientLaneConfig clientLaneConfig = new ClientLaneConfig();
            clientLaneConfig.setClientId(Long.valueOf(request.getClientId()));
            clientLaneConfig.setLaneId(Long.valueOf(laneId));
            clientLaneConfig.setSort(++sort);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoSwitch", "on");
            jsonObject.put("remoteVideoSwitch", "off");
            jsonObject.put("localVideoSwitch", "on");
            jsonObject.put("temPark", "on");
            clientLaneConfig.setConfig(jsonObject.toString());
            clientLaneConfigs.add(clientLaneConfig);
        }
        int i = clientLaneConfigMapper.batchInsertClientLaneConfig(clientLaneConfigs);
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult cancelLane(ParkClientSelectLaneRequest request) {
        String laneId = request.getLaneId();
        int i;
        if (StringUtils.isNotEmpty(laneId)) {
            parkLaneMapper.batchClearClientLane(Collections.singletonList(laneId));
            //删除中间表信息
            ClientLaneConfig clientLaneConfig = new ClientLaneConfig();
            clientLaneConfig.setLaneId(Long.valueOf(request.getLaneId()));
            clientLaneConfig.setClientId(Long.valueOf(request.getClientId()));
            i = clientLaneConfigMapper.deleteClientLaneConfig(clientLaneConfig);
        } else {
            List<String> laneIds = Arrays.asList(request.getLaneIds().split(","));
            List<ClientLaneConfig> clientLaneConfigs = new ArrayList<>();
            laneIds.forEach(e -> {
                ClientLaneConfig clientLaneConfig = new ClientLaneConfig();
                clientLaneConfig.setLaneId(Long.valueOf(e));
                clientLaneConfig.setClientId(Long.valueOf(request.getClientId()));
                clientLaneConfigs.add(clientLaneConfig);
            });
            //批量删除中间表信息
            i = clientLaneConfigMapper.batchDeleteClientLaneConfig(clientLaneConfigs);
        }

        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult editParkOnPlate(ClientPlateEditRequest request) {
        ParkOn search = new ParkOn();
        search.setPlate(request.getPlate());
        List<ParkOn> parkOns = parkOnService.selectParkOnList(search);
        if (!parkOns.isEmpty()) {
            return AjaxResult.error("车牌已入场");
        }
        String plateNew = request.getPlate();
        ParkOn parkOn = parkOnService.selectParkOnById(Long.valueOf(request.getRecordId()));
        // 将操作人字段赋值
        parkOn.setUpdateUser(Long.valueOf(request.getUpdateUserId()));
        parkOn.setIsUpdate("Y");

        // 入场记录修改记录保存
        ParkIn parkIn = parkInService.selectParkInById(parkOn.getInId());
        if (null != parkIn) {
            parkIn.setUpdateUser(Long.valueOf(request.getUpdateUserId()));
            parkIn.setIsUpdate("Y");
            if (StringUtils.isNotEmpty(plateNew)) {
                parkOn.setPlate(plateNew);
                parkIn.setInCarPlate(plateNew);
            }

            parkInService.updateParkIn(parkIn);
        }
        return AjaxResult.success();
    }

    @Override
    public List<OpenGateVo> selectOpenGateRecords(OpenGateRequest request) {
        List<OpenGateVo> openGateVoList = parkClientMapper.selectOpenGateRecords(request);
        if (CollectionUtil.isNotEmpty(openGateVoList)) {
            openGateVoList.forEach(openGateVo -> {
                Long oprClientUserId = openGateVo.getOprClientUser();
                Long oprUserId = openGateVo.getOprUser();
                Long updateUserId = oprClientUserId != null ? oprClientUserId : oprUserId;
                if (updateUserId != null) {
                    R<OperateDTO> operateDtoResult = remoteSystemUserService.getOperate(updateUserId);
                    if (operateDtoResult.getData() != null) {
                        openGateVo.setUpdateBy(operateDtoResult.getData().getOperateName());
                    }
                }
                openGateVo.setPic(StringUtils.isNotEmpty(openGateVo.getPic()) ? aliossUtil.getJzyGetObjectUrl(openGateVo.getPic()).toString() : "");
            });

        }
        return openGateVoList;
    }

}
